package com.fjwt.gz.service.activity.coupon.send;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.coupon.SendCouponBo;
import com.fjwt.gz.coupon.yspay.YspayCouponSendService;
import com.fjwt.gz.db.bo.CouponResultBo;
import com.fjwt.gz.db.entity.FansPayEntity;
import com.fjwt.gz.db.entity.PayAuthEntity;
import com.fjwt.gz.db.entity.SysConfig;
import com.fjwt.gz.interfaces.ISendCouponService;
import com.fjwt.gz.service.impl.FansPayService;
import com.fjwt.gz.service.mapper.SysConfigMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class YspaySendCouponService implements ISendCouponService {
    private static final Logger ysPayLogger = LoggerFactory.getLogger("ysPay");

    @Autowired
    private FansPayService fansPayService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private YspayCouponSendService yspayCouponSendService;

    @Override
    public CouponResultBo couponSend(PayAuthEntity authEntity, Long fansId, @NonNull String payConfig, Long couponId) {

        ysPayLogger.info("银盛发券，支付通道方出资信息：{}，fansId：{}，,卡券payConfig：{}",
                JSON.toJSONString(authEntity), fansId, JSONUtil.toJsonStr(payConfig));
        SendCouponBo sendCouponBo = new SendCouponBo();

        LambdaQueryWrapper<FansPayEntity> gw = FansPayEntity.gw();
        gw.eq(FansPayEntity::getIfCode, authEntity.getIfCode());
        gw.eq(FansPayEntity::getFansId, fansId);
        FansPayEntity fansOpen = fansPayService.getOne(gw);

        LambdaQueryWrapper<SysConfig> sysgw = SysConfig.gw();
        sysgw.eq(SysConfig::getConfigKey, "yspay");
        SysConfig sysConfig = sysConfigMapper.selectOne(sysgw);

        sendCouponBo.setOpenId(fansOpen.getOpenId());
        sendCouponBo.setStockId(payConfig);
        sendCouponBo.setAuthConfig(JSONObject.parseObject(sysConfig.getConfigVal()));
        JSONObject jsonObject = yspayCouponSendService.couponSend(sendCouponBo);

        String couponThirdId = jsonObject.getString("couponId");
        CouponResultBo couponResultBo = new CouponResultBo();
        couponResultBo.setCouponThirdId(couponThirdId);
        couponResultBo.setStockId(payConfig);

        return couponResultBo;
    }
}
